package net.huashitong.gradePoint.service;


import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysLoginDao;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.gradePoint.dao.ScoreSummaryDao;
import net.huashitong.gradePoint.databean.DepartRank;
import net.huashitong.gradePoint.entity.GradePoint;
import net.huashitong.gradePoint.entity.ScoreSummary;
import net.huashitong.gradePoint.filter.ScoreSummaryFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static net.huashitong.utils.UtilsTools.getCurrentDateTime1;

@Service
public class ScoreSummaryService extends StringPKService<ScoreSummary> {

    @Autowired
    private ScoreSummaryDao dao;
    @Autowired
    private GradePointService gradePointService;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysLoginDao sysLoginDao;

    @Override
    protected BaseDao<ScoreSummary, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(ScoreSummary obj) {
        obj.setSysId(tableService.updateMaxSysId("t_scoresummary", null));
    }


    public List<ScoreSummary> queryByFilter(ScoreSummaryFilter filter) {
        return dao.queryByFilter(filter);
    }

    public List<ScoreSummary> queryByFilterNoPage(ScoreSummaryFilter filter) {
        return dao.queryByFilterNoPage(filter);
    }

    /**
     * 汇总得分
     */
    public void updateSummaryScore() {
        List<ScoreSummary> resultList = new ArrayList<>();
        List<ScoreSummary> resultList1 = new ArrayList<>();
        List<ScoreSummary> resultList2 = new ArrayList<>();
        List<ScoreSummary> resultList3 = new ArrayList<>();
        List<ScoreSummary> oldScoreSummary = query();
        //绩效得分
        Map<String, Double> userScoreMap = new HashMap<>();
        //绩效考核次数
        Map<String, Integer> userCountMap = new HashMap<>();

        //所有绩效评分情况（已完成、已考核的绩效评分）
        List<GradePoint> gradePoints = gradePointService.queryChecked();
        for (GradePoint g : gradePoints) {
            if (!userScoreMap.containsKey(g.getCheckObjectId())) {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                userScoreMap.put(g.getCheckObjectId(), score);
                userCountMap.put(g.getCheckObjectId(), 1);
            } else {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                Double newScore = userScoreMap.get(g.getCheckObjectId()) + score;
                userScoreMap.put(g.getCheckObjectId(), newScore);
                int count = userCountMap.get(g.getCheckObjectId());
                count++;
                userCountMap.put(g.getCheckObjectId(), count);
            }
        }
        List<SysUser> users = sysUserService.query();
        //封装用户
        Map<String, SysUser> userMap = new HashMap<>();
        Map<String, ScoreSummary> inspectorsMap = new HashMap<>();
        for(SysUser u : users){
            if(!userMap.containsKey(u.getSysId())){
                userMap.put(u.getSysId(),u);
            }
        }

        for (Map.Entry<String, Double> entry : userScoreMap.entrySet()) {
            ScoreSummary summary = new ScoreSummary();

            String userId = entry.getKey();
            double allScore = entry.getValue();
            double resScore = 0.0;

            if(ObjectUtils.isNotBlank(userMap.get(userId))){
                resScore = allScore/ (userCountMap.get(userId)) +
                        allScore / 10;
                SysUser user = userMap.get(userId);

                SysDept sysDept = this.queryDeptByUserId(user.getSysId());

                summary.setCheckDept(sysDept.getDeptName());
                summary.setCheckObject(userMap.get(userId).getName());
                summary.setScore(String.format("%.2f", resScore) + "");
                summary.setUserId(userMap.get(userId).getSysId());
                summary.setSummaryDate(getCurrentDateTime1());
                //责任单位
                if("1".equals(userMap.get(userId).getSuperFlag())){
                    summary.setBranchType("res");
                }
                if("0".equals(userMap.get(userId).getSuperFlag())){
                    summary.setBranchType("sup");
                }
            }
            //出现两个督查组的情况
//            if(StringUtils.isBlank(summary.getScore())){
//                String [] userIds = userId.split(",");
//                for(String u : userIds){
//                    ScoreSummary summary2 = new ScoreSummary();
//                    resScore = allScore / (userCountMap.get(userId)) +
//                            allScore / 10;
//                    summary2.setCheckDept(jobGroupMap.get(u).getGroupDuty());
//                    summary2.setCheckObject(jobGroupMap.get(u).getGroupName());
//                    summary2.setScore(String.format("%.2f", resScore) + "");
//                    summary2.setUserId(jobGroupMap.get(u).getGroupCode());
//                    summary2.setSummaryDate(getCurrentDateTime1());
//                    summary2.setBranchType("4");
//                    resultList2.add(summary2);
//                }
//                continue;
//            }
            resultList.add(summary);
        }

        for(ScoreSummary list1 : resultList1){
            if(!inspectorsMap.containsKey(list1.getUserId())){
                inspectorsMap.put(list1.getUserId(),list1);
            }
        }
        for(ScoreSummary list2 : resultList2){
            ScoreSummary re = inspectorsMap.get(list2.getUserId());
            if(ObjectUtils.isNotBlank(re)){
                double scoreDouble = Double.parseDouble(re.getScore())+Double.parseDouble(list2.getScore());
                re.setScore(scoreDouble+"");
                inspectorsMap.put(list2.getUserId(),re);
            }else{
                resultList3.add(list2);
            }
        }

        for (Map.Entry<String, ScoreSummary> inspectors : inspectorsMap.entrySet()) {
            ScoreSummary summary = inspectors.getValue();
            resultList3.add(summary);
        }
        resultList.addAll(resultList3);
        batchDeleteObject(oldScoreSummary);
        batchSave(resultList);
    }

    public void updateSummaryScoreRank(){
        List<ScoreSummary> summaries = this.query();
        Collections.sort(summaries, new Comparator<ScoreSummary>() {
            @Override
            public int compare(ScoreSummary g1, ScoreSummary g2) {
                double score1 = Double.parseDouble(StringUtils.isBlank(g1.getScore()) ? "0" : g1.getScore());
                double score2 = Double.parseDouble(StringUtils.isBlank(g2.getScore()) ? "0" : g2.getScore());
                if (score1 < score2) {
                    return 1;
                } else if (score1 == score2) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        for (int i = 0, s = summaries.size(); i < s; i++) {
            if (i > 0 && Double.parseDouble(StringUtils.isBlank(summaries.get(i).getScore()) ? "0" : summaries.get(i).getScore())
                    == Double.parseDouble(StringUtils.isBlank(summaries.get(i - 1).getScore()) ? "0" : summaries.get(i - 1).getScore())) {
                summaries.get(i).setRank(summaries.get(i - 1).getRank());
            } else {
                summaries.get(i).setRank(i + 1 + "");
            }
        }
        this.batchUpdate(summaries);
    }
    /**
     * 更新汇总得分中分组别的排名情况（TypeRank）
     */
    public void updateSummaryScoreTypeRank(){
        ScoreSummaryFilter filter = new ScoreSummaryFilter();
        List<String> branchTypes = new ArrayList<>();
        branchTypes.add("0");
        branchTypes.add("1");
        branchTypes.add("4");
        for(String b : branchTypes){
            filter.setBranchType(b);
            List<ScoreSummary> summaries = this.queryByFilterNoPage(filter);
            Collections.sort(summaries, new Comparator<ScoreSummary>() {
                @Override
                public int compare(ScoreSummary g1, ScoreSummary g2) {
                    double score1 = Double.parseDouble(StringUtils.isBlank(g1.getScore()) ? "0" : g1.getScore());
                    double score2 = Double.parseDouble(StringUtils.isBlank(g2.getScore()) ? "0" : g2.getScore());
                    if (score1 < score2) {
                        return 1;
                    } else if (score1 == score2) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
            for (int i = 0, s = summaries.size(); i < s; i++) {
                if (i > 0 && Double.parseDouble(StringUtils.isBlank(summaries.get(i).getScore()) ? "0" : summaries.get(i).getScore())
                        == Double.parseDouble(StringUtils.isBlank(summaries.get(i - 1).getScore()) ? "0" : summaries.get(i - 1).getScore())) {
                    summaries.get(i).setTypeRank(summaries.get(i - 1).getTypeRank());
                } else {
                    summaries.get(i).setTypeRank(i + 1 + "");
                }
            }
            this.batchUpdate(summaries);
        }
    }

    public List<ScoreSummary> queryScoreSummaryByIds(List<String> ids){
        return dao.queryScoreSummaryByIds(ids);
    }

    public List<DepartRank> queryDepartRank(ScoreSummaryFilter filter){return dao.queryDepartRank(filter); }

    public List<DepartRank> queryDepartRankNoPage(ScoreSummaryFilter filter){
        return dao.queryDepartRankNoPage(filter);
    }

    /**
     * 根据userId查询部门
     * @param userId
     * @return
     */
    public SysDept queryDeptByUserId(String userId){
        SysLogin sysLogin = sysLoginDao.getLoginByUserId(userId);
        String deptId = sysLogin.getDeptId();
        SysDept sysDept = sysDeptService.getById(deptId);
        return sysDept;
    }

}
